package cloud.xlh.my_system.service.impl;

import cloud.xlh.my_system.exception.NotExistException;
import cloud.xlh.my_system.middle_aware.redis.utils.RedisUtil;
import cloud.xlh.my_system.service.TokenService;
import com.alibaba.druid.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

/**
 * Created with IntelliJ IDEA.
 *
 * @ project name : xlh_osms
 * @ Author: XuLeHuang
 * @ Date: 2022/5/27 16:24
 * @ Description:
 */
@Service
public class TokenServiceImpl implements TokenService {
    @Autowired
    private RedisUtil redisUtil;

    @Override
    public String getToken(){
        String token = UUID.randomUUID().toString();
        return token;
    }

        /**
         * 标注了@Idempotent注解的方法，请求的时候就会到这里
        * */
    public boolean checkToken(HttpServletRequest request) throws NotExistException {
        // 请求头中获取token
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)){
            // 请求体中获取token
            token = request.getParameter("token");
            if (StringUtils.isEmpty(token)){
                throw new NotExistException("请携带token访问");
            }
        }
        //同一个请求编号只能一次请求
        if (redisUtil.exist("xlh_osms-" + token)){
            throw new NotExistException("重复请求");
        } else {
            //第一次访问就会生成一条幂等表记录
            redisUtil.set("xlh_osms-" + token,"PROC",10000L);
        }
        return true;
    }

    /**
     * 标注了@Idempotent注解的方法，响应的时候就会到这里
     * */
    @Override
    public void updateToken(HttpServletRequest request) {
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)){
            // 请求体中获取token
            token = request.getParameter("token");
            if (StringUtils.isEmpty(token)){
                throw new NotExistException("请携带token访问");
            }
        }
        redisUtil.set("xlh_osms-" + token ,  "OK" ,  30000L);
    }
}
